package com.example.ywj.toutiao.utils;

import android.content.Context;
import android.content.DialogInterface;
import android.graphics.Typeface;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.TextView;

import com.bumptech.glide.Glide;
import com.bumptech.glide.request.RequestOptions;
import com.example.ywj.toutiao.R;
import com.example.ywj.toutiao.bean.News;
import com.google.gson.JsonObject;
import com.google.gson.JsonParser;

import java.io.IOException;
import java.text.DecimalFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;

import androidx.appcompat.app.AlertDialog;
import es.dmoral.toasty.Toasty;
import okhttp3.ResponseBody;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;
import retrofit2.Retrofit;
import retrofit2.converter.gson.GsonConverterFactory;

public class MyBaseAdapter extends BaseAdapter {
    private static final String TAG = "MyBaseAdapter";
    private List<News> list ;
    private String baseUrl = Constant.BASEURL;
    public MyBaseAdapter(List<News> list){
        Log.i(TAG, "MyBaseAdapter: "+list);
        this.list = list;
    }
    @Override
    public int getCount() {
        Log.i(TAG, "getCount: "+list.size());
        return list.size();
    }

    @Override
    public Object getItem(int position) {
        return list.get(position);
    }

    @Override
    public long getItemId(int position) {
        return position;
    }

    @Override
    public View getView(final int position, View convertView, final ViewGroup parent) {
        int currentType = getItemViewType(position);
        if(currentType == 0){
            Item1ViewHolder item1ViewHolder ;
            if(convertView == null){
                //获取布局管理器
                LayoutInflater inflater = LayoutInflater.from(parent.getContext());
                convertView = inflater.inflate(R.layout.news_item1,null);
                item1ViewHolder = new Item1ViewHolder();
                item1ViewHolder.tv_title1 = convertView.findViewById(R.id.item1_title);
                item1ViewHolder.item1_img1 = convertView.findViewById(R.id.item1_img01);
                item1ViewHolder.item1_img2 = convertView.findViewById(R.id.item1_img02);
                item1ViewHolder.item1_img3 = convertView.findViewById(R.id.item1_img03);
                item1ViewHolder.item1_author = convertView.findViewById(R.id.item1_author);
                item1ViewHolder.item1_comment = convertView.findViewById(R.id.item1_comment);
                item1ViewHolder.item1_time = convertView.findViewById(R.id.item1_time);
                item1ViewHolder.item1_delete = convertView.findViewById(R.id.item1_delete);
                item1ViewHolder.item1_hot = convertView.findViewById(R.id.item1_hot);
                convertView.setTag(item1ViewHolder);
            }else{
                item1ViewHolder = (Item1ViewHolder)convertView.getTag();
            }
            //Log.i(TAG, "getView: "+item1ViewHolder.tv_title1);
            //Log.i(TAG, "getView: "+list.get(position).getTitle());
            String images = list.get(position).getImages();
            String []image = images.split("&");
            String imgUrl1 = baseUrl+"public/images/"+image[0]+".jpg";
            String imgUrl2 = baseUrl+"public/images/"+image[1]+".jpg";
            String imgUrl3 = baseUrl+"public/images/"+image[2]+".jpg";
            item1ViewHolder.tv_title1.setText(list.get(position).getTitle());
            item1ViewHolder.item1_author.setText(list.get(position).getAuthor());
            item1ViewHolder.item1_comment.setText(list.get(position).getComment()+"评论");
            item1ViewHolder.item1_time.setText(showTime(list.get(position).getTime()));
            RequestOptions requestOptions = new RequestOptions();
            requestOptions.placeholder(R.drawable.placeholder).error(R.drawable.error_img);
            Glide.with(parent.getContext()).load(imgUrl1).apply(requestOptions).into(item1ViewHolder.item1_img1);
            Glide.with(parent.getContext()).load(imgUrl2).apply(requestOptions).into(item1ViewHolder.item1_img2);
            Glide.with(parent.getContext()).load(imgUrl3).apply(requestOptions).into(item1ViewHolder.item1_img3);
            Typeface font = Typeface.createFromAsset(convertView.getContext().getAssets(), "iconfont.ttf");
            item1ViewHolder.item1_delete.setTypeface(font);
            item1ViewHolder.item1_delete.setText(convertView.getContext().getResources().getString(R.string.font9));
            item1ViewHolder.item1_hot.setTypeface(font);
            item1ViewHolder.item1_hot.setText(convertView.getContext().getResources().getString(R.string.font8));

            item1ViewHolder.item1_delete.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    AlertDialog.Builder builder = new AlertDialog.Builder(parent.getContext());
                    //    指定下拉列表的显示数据
                    final String[] cities = {"不感兴趣，减少这类内容","反馈垃圾内容"};
                    //    设置一个下拉的列表选择项
                    builder.setItems(cities, new DialogInterface.OnClickListener()
                    {
                        @Override
                        public void onClick(DialogInterface dialog, int which)
                        {
                            //Toast.makeText(parent.getContext(), "选择的城市为：" + which, Toast.LENGTH_SHORT).show();
                            if(which == 0){
                                updateNews(list.get(position).get_id(),parent.getContext());
                            }else if(which == 1){
                                updateNews(list.get(position).get_id(),parent.getContext());
                            }

                        }
                    });
                    builder.show();
                }
            });
        }else if(currentType == 1){
            Item2ViewHolder item2ViewHolder ;
            if(convertView == null){
                //获取布局管理器
                LayoutInflater inflater = LayoutInflater.from(parent.getContext());
                convertView = inflater.inflate(R.layout.news_item2,null);
                item2ViewHolder = new Item2ViewHolder();
                item2ViewHolder.tv_title2 = convertView.findViewById(R.id.item2_title);
                item2ViewHolder.item2_img = convertView.findViewById(R.id.item2_img);
                item2ViewHolder.item2_author = convertView.findViewById(R.id.item2_author);
                item2ViewHolder.item2_comment = convertView.findViewById(R.id.item2_comment);
                item2ViewHolder.item2_time = convertView.findViewById(R.id.item2_time);
                item2ViewHolder.item2_hot = convertView.findViewById(R.id.item2_hot);
                item2ViewHolder.item2_delete = convertView.findViewById(R.id.item2_delete);
                convertView.setTag(item2ViewHolder);
            }else{
                item2ViewHolder = (Item2ViewHolder)convertView.getTag();
            }
            RequestOptions requestOptions = new RequestOptions();
            requestOptions.placeholder(R.drawable.placeholder).error(R.drawable.error_img);
            String images = list.get(position).getImages();
            String []image = images.split("&");
            String imgUrl1 = baseUrl+"public/images/"+image[0]+".jpg";
            item2ViewHolder.tv_title2.setText(list.get(position).getTitle());
            item2ViewHolder.item2_author.setText(list.get(position).getAuthor());
            item2ViewHolder.item2_comment.setText(list.get(position).getComment()+"评论");
            item2ViewHolder.item2_time.setText(showTime(list.get(position).getTime()));
            Glide.with(parent.getContext()).load(imgUrl1).apply(requestOptions).into(item2ViewHolder.item2_img);
            Typeface font = Typeface.createFromAsset(convertView.getContext().getAssets(), "iconfont.ttf");
            item2ViewHolder.item2_delete.setTypeface(font);
            item2ViewHolder.item2_delete.setText(convertView.getContext().getResources().getString(R.string.font9));
            item2ViewHolder.item2_hot.setTypeface(font);
            item2ViewHolder.item2_hot.setText(convertView.getContext().getResources().getString(R.string.font8));
            item2ViewHolder.item2_delete.setOnClickListener(new View.OnClickListener(){
                @Override
                public void onClick(View v) {
                    AlertDialog.Builder builder = new AlertDialog.Builder(parent.getContext());
                    //    指定下拉列表的显示数据
                    final String[] cities = {"不感兴趣，减少这类内容","反馈垃圾内容"};
                    //    设置一个下拉的列表选择项
                    builder.setItems(cities, new DialogInterface.OnClickListener()
                    {
                        @Override
                        public void onClick(DialogInterface dialog, int which)
                        {
                            //Toast.makeText(parent.getContext(), "选择的城市为：" + which, Toast.LENGTH_SHORT).show();
                            if(which == 0){
                                updateNews(list.get(position).get_id(),parent.getContext());
                            }else if(which == 1){
                                updateNews(list.get(position).get_id(),parent.getContext());
                            }

                        }
                    });
                    builder.show();
                }
            });
        }else if(currentType == 2){
            Item3ViewHolder item3ViewHolder ;
            if(convertView == null){
                //获取布局管理器
                LayoutInflater inflater = LayoutInflater.from(parent.getContext());
                convertView = inflater.inflate(R.layout.news_item3,null);
                item3ViewHolder = new Item3ViewHolder();
                item3ViewHolder.tv_title3 = convertView.findViewById(R.id.item3_title);
                item3ViewHolder.item3_img = convertView.findViewById(R.id.item3_img);
                item3ViewHolder.item3_author = convertView.findViewById(R.id.item3_author);
                item3ViewHolder.item3_comment = convertView.findViewById(R.id.item3_comment);
                item3ViewHolder.item3_delete = convertView.findViewById(R.id.item3_delete);
                convertView.setTag(item3ViewHolder);
            }else{
                item3ViewHolder = (Item3ViewHolder)convertView.getTag();
            }
            RequestOptions requestOptions = new RequestOptions();
            requestOptions.placeholder(R.drawable.placeholder).error(R.drawable.error_img);
            String images = list.get(position).getImages();
            String []image = images.split("&");
            String imgUrl1 = baseUrl+"public/images/"+image[0]+".jpg";
            item3ViewHolder.tv_title3.setText(list.get(position).getTitle());
            item3ViewHolder.item3_author.setText(list.get(position).getAuthor());
            item3ViewHolder.item3_comment.setText(list.get(position).getComment()+"评论");
            Glide.with(parent.getContext()).load(imgUrl1).apply(requestOptions).into(item3ViewHolder.item3_img);
            Typeface font = Typeface.createFromAsset(convertView.getContext().getAssets(), "iconfont.ttf");
            item3ViewHolder.item3_delete.setTypeface(font);
            item3ViewHolder.item3_delete.setText(convertView.getContext().getResources().getString(R.string.font9));
            item3ViewHolder.item3_delete.setOnClickListener(new View.OnClickListener(){
                @Override
                public void onClick(View v) {
                    AlertDialog.Builder builder = new AlertDialog.Builder(parent.getContext());
                    //    指定下拉列表的显示数据
                    final String[] cities = {"不感兴趣，减少这类内容","反馈垃圾内容"};
                    //    设置一个下拉的列表选择项
                    builder.setItems(cities, new DialogInterface.OnClickListener()
                    {
                        @Override
                        public void onClick(DialogInterface dialog, int which)
                        {
                           // Toast.makeText(parent.getContext(), "选择的城市为：" + which, Toast.LENGTH_SHORT).show();
                            if(which == 0){
                                updateNews(list.get(position).get_id(),parent.getContext());
                            }else if(which == 1){
                                updateNews(list.get(position).get_id(),parent.getContext());
                            }

                        }
                    });
                    builder.show();
                }
            });
        }else if(currentType == 3){
            Item4ViewHolder item4ViewHolder ;
            if(convertView == null) {
                //获取布局管理器
                LayoutInflater inflater = LayoutInflater.from(parent.getContext());
                convertView = inflater.inflate(R.layout.news_item4, null);
                item4ViewHolder = new Item4ViewHolder();
                item4ViewHolder.item4_avatar = convertView.findViewById(R.id.item4_avatar);
                item4ViewHolder.item4_content_pic = convertView.findViewById(R.id.item4_content_pic);
                item4ViewHolder.item4_nickname = convertView.findViewById(R.id.item4_nickname);
                item4ViewHolder.item4_time = convertView.findViewById(R.id.item4_time);
                item4ViewHolder.item4_delete = convertView.findViewById(R.id.item4_delete);
                item4ViewHolder.item4_content = convertView.findViewById(R.id.item4_content_text);
                convertView.setTag(item4ViewHolder);
            }else{
                item4ViewHolder = (Item4ViewHolder)convertView.getTag();
            }
            RequestOptions requestOptions = new RequestOptions();
            requestOptions.placeholder(R.drawable.placeholder).error(R.drawable.error_img);
            String images = list.get(position).getImages();
            String []image = images.split("&");
            String imgUrl1 = baseUrl+"public/images/"+image[0]+".jpg";
            String imgUrl2 = baseUrl+"public/images/"+list.get(position).getAvatar()+".jpg";
            Glide.with(parent.getContext()).load(imgUrl1).apply(requestOptions).into(item4ViewHolder.item4_content_pic);
            Glide.with(parent.getContext()).load(imgUrl2).apply(requestOptions).into(item4ViewHolder.item4_avatar);
            item4ViewHolder.item4_nickname.setText(list.get(position).getAuthor());
            item4ViewHolder.item4_time.setText(showTime(list.get(position).getTime()));
            item4ViewHolder.item4_content.setText(list.get(position).getTitle());
            Typeface font = Typeface.createFromAsset(convertView.getContext().getAssets(), "iconfont.ttf");
            item4ViewHolder.item4_delete.setTypeface(font);
            item4ViewHolder.item4_delete.setText(convertView.getResources().getString(R.string.font9));
            item4ViewHolder.item4_delete.setOnClickListener(new View.OnClickListener(){
                @Override
                public void onClick(View v) {
                    AlertDialog.Builder builder = new AlertDialog.Builder(parent.getContext());
                    //    指定下拉列表的显示数据
                    final String[] cities = {"不感兴趣，减少这类内容","反馈垃圾内容"};
                    //    设置一个下拉的列表选择项
                    builder.setItems(cities, new DialogInterface.OnClickListener()
                    {
                        @Override
                        public void onClick(DialogInterface dialog, int which)
                        {
                            // Toast.makeText(parent.getContext(), "选择的城市为：" + which, Toast.LENGTH_SHORT).show();
                            if(which == 0){
                                updateNews(list.get(position).get_id(),parent.getContext());
                            }else if(which == 1){
                                updateNews(list.get(position).get_id(),parent.getContext());
                            }

                        }
                    });
                    builder.show();
                }
            });
        }
        return convertView;
    }

    @Override
    public int getItemViewType(int position) {
       if(list.get(position).getNewType() == 1){
           return 0;
       }else if(list.get(position).getNewType() == 2){
           return 1;
       }else if(list.get(position).getNewType() == 3){
           return 2;
       }else if(list.get(position).getNewType()==4){
            return 3;
       }else{
           return 100;
       }
    }

    @Override
    public int getViewTypeCount() {
        return 4;
    }
    class Item1ViewHolder{
        TextView tv_title1;
        ImageView item1_img1;
        ImageView item1_img2;
        ImageView item1_img3;
        TextView item1_author;
        TextView item1_comment;
        TextView item1_time;
        TextView item1_delete;
        TextView item1_hot;
    }
    class Item2ViewHolder{
        TextView tv_title2;
        ImageView item2_img;
        TextView item2_author;
        TextView item2_comment;
        TextView item2_time;
        TextView item2_delete;
        TextView item2_hot;
    }
    class Item3ViewHolder{
        TextView tv_title3;
        TextView item3_author;
        TextView item3_comment;
        ImageView item3_img;
        TextView item3_delete;
    }
    class Item4ViewHolder{
        ImageView item4_avatar;
        ImageView item4_content_pic;
        TextView item4_nickname;
        TextView item4_time;
        TextView item4_delete;
        TextView item4_content;
    }
    public String showTime(String str) {
        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        SimpleDateFormat format1 = new SimpleDateFormat("yyyy-MM-dd");
        Date date = null;
        String showStrTimes = "";
        try {
            date = format.parse(str);
        } catch (ParseException e) {
            e.printStackTrace();
        }
        long oldTimes = date.getTime();
        long newTimes = new Date().getTime();
        if(newTimes - oldTimes >= 86400000) {
            DecimalFormat decimalFormat = new DecimalFormat("###################.###########");
            showStrTimes = decimalFormat.format(Math.floor((newTimes - oldTimes)/86400000))+"天前";
        }else {
            showStrTimes = format1.format(oldTimes);
        }
        return showStrTimes;
    }
    public void updateNews(String id, final Context context){
        Retrofit retrofit = new Retrofit.Builder()
                .addConverterFactory(GsonConverterFactory.create())
                .baseUrl(baseUrl)
                .build();
        ResponseApi responseApi = retrofit.create(ResponseApi.class);
        Call<ResponseBody> call = responseApi.updateNews(id);
        call.enqueue(new Callback<ResponseBody>() {
            @Override
            public void onResponse(Call<ResponseBody> call, Response<ResponseBody> response) {
                String json = null;
                try {
                    json = response.body().string();
                    //Log.i(TAG, "onResponse: "+json);
                } catch (IOException e) {
                    e.printStackTrace();
                }
                JsonObject obj = (JsonObject)new JsonParser().parse(json);
                Integer code = obj.get("statusCode").getAsInt();
                if(code == 200 && obj.has("data")){
                    Toasty.info(context,"感谢您的反馈",Toasty.LENGTH_LONG).show();
                }
            }
            @Override
            public void onFailure(Call<ResponseBody> call, Throwable t) {

            }
        });
    }
}

